package com.example.exception;

import com.example.result.ResultApi;
import com.example.util.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description 全局异常统一处理
 * @Author Moran
 * @Date 2023-06-04 19:01
 */
@RestControllerAdvice
public class GlobalException {
    private final static Logger log = LoggerFactory.getLogger(GlobalException.class);
    /**
     * 处理自定义异常
     */
    @ExceptionHandler(value = BadRequestException.class)
    public ResponseEntity<ResultApi> badRequestException(BadRequestException e) {
        // 打印堆栈信息
        log.error(ThrowableUtil.getStackTrace(e));
        return buildResponseEntity(ResultApi.error(e.getMessage(), e.getStatus()));
    }

    /**
     * 统一返回
     */
    private ResponseEntity<ResultApi> buildResponseEntity(ResultApi apiError) {
        return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
    }
}
